package com.yuma.springaialibaba.controller;

import com.alibaba.cloud.ai.dashscope.image.DashScopeImageModel;
import com.alibaba.cloud.ai.dashscope.image.DashScopeImageOptions;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.ai.image.ImagePrompt;
import org.springframework.ai.image.ImageResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.io.InputStream;
import java.net.URI;
import java.net.URL;

@RestController
public class AliImageModelController {
    @Autowired
    private DashScopeImageModel imageModel;
    @GetMapping("/ali/images/{msg}")
    public void getImage(@PathVariable String msg, HttpServletResponse response) {
        try {

            DashScopeImageOptions imageOptions = DashScopeImageOptions.builder().build();
            imageOptions.setModel("wanx2.1-t2i-turbo");

            ImageResponse imageResponse = imageModel.call(
                    new ImagePrompt(msg, imageOptions));
            String imageUrl = imageResponse.getResult().getOutput().getUrl();
            // 把生成的图片的网址内容写到网页上
            URL url = URI.create(imageUrl).toURL();
            InputStream inputStream = url.openStream();
            response.setHeader("Content-Type", MediaType.IMAGE_PNG_VALUE);
            response.getOutputStream().write(inputStream.readAllBytes());
            response.getOutputStream().flush();
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

}
